package com.yunban.project.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunban.project.template.mapper.TemplateGroupMapMapper;
import com.yunban.project.template.model.domain.Template;
import com.yunban.project.template.model.domain.TemplateGroupMap;
import com.yunban.project.template.model.domain.Type;
import com.yunban.project.template.model.dto.AddTemplateToGroupReq;
import com.yunban.project.template.model.dto.BatchSaveTemplateToGroupReq;
import com.yunban.project.template.model.dto.RemoveTemplateGroupMapReq;
import com.yunban.project.template.model.vo.TemplateResp;
import com.yunban.project.template.model.vo.TypeResp;
import com.yunban.project.template.service.TemplateGroupMapService;
import com.yunban.project.template.service.TemplateGroupService;
import com.yunban.project.template.service.TemplateService;
import com.yunban.project.template.service.TypeService;
import jakarta.annotation.Resource;
import net.lab1024.sa.base.common.exception.BusinessException;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class TemplateGroupMapServiceImpl extends ServiceImpl<TemplateGroupMapMapper, TemplateGroupMap> implements TemplateGroupMapService {

    @Resource
    private TemplateService templateService;

    @Resource
    private TemplateGroupService templateGroupService;

    @Resource
    private TypeService typeService;

    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public Boolean batchSaveTemplateToGroup(long groupId, BatchSaveTemplateToGroupReq req) {
        // 获取模板组是否存在
        this.templateGroupService.findById(groupId);
        List<TemplateResp> templates = SmartPageUtil.convert(this.templateService.listByIds(req.getTemplateIds()), TemplateResp.class);
        if (req.getTemplateIds().size() != templates.size()) {
            throw new BusinessException("模板信息错误~");
        }
        // 合并
        templates.addAll(this.findByGroupId(groupId));
        // 获取这个组下所有的模板
        // 随后需要判断是否已经存在该类型模板
        // 通过 stream 对 templates 通过  blockTypeId 进行分组
        Map<Long, List<TemplateResp>> groupedTemplates = templates.stream().collect(Collectors.groupingBy(TemplateResp::getBlockTypeId));
        // 获取所有的模板类型信息
        List<Type> typeList = this.typeService.list();
        // 将 typeList 转为 map
        Map<Long, Type> typeMap = typeList.stream().collect(Collectors.toMap(Type::getId, Function.identity()));
        // 循环 groupedTemplates
        for (Long typeId : groupedTemplates.keySet()) {
            List<TemplateResp> templateList = groupedTemplates.get(typeId);
            if (templateList.size() > 1) {
                throw new BusinessException("模板类型:" + typeMap.get(typeId).getName() + "有重复~");
            }
        }
        List<TemplateGroupMap> r = new ArrayList<>();
        for (Long templateId : req.getTemplateIds()) {
            TemplateGroupMap templateGroupMap = new TemplateGroupMap();
            templateGroupMap.setGroupId(groupId);
            templateGroupMap.setTemplateId(templateId);
            r.add(templateGroupMap);
        }
        return this.saveBatch(r);
    }

    @Override
    public Boolean addTemplateToGroup(long groupId, AddTemplateToGroupReq req) {
        // 获取模板组是否存在
        this.templateGroupService.findById(groupId);
        Long templateId = req.getTemplateId();
        Template template = this.templateService.findById(templateId);
        // 获取所有的模板类型信息
        List<Type> typeList = this.typeService.list();
        // 将 typeList 转为 map
        Map<Long, Type> typeMap = typeList.stream().collect(Collectors.toMap(Type::getId, Function.identity()));
        List<TemplateResp> templateRespList = this.findByGroupId(groupId);
        // 判断这种类型是否已经在库中
        templateRespList.forEach(items -> {
            if (template.getBlockTypeId() == items.getBlockTypeId()) {
                throw new BusinessException("模板类型:" + typeMap.get(items.getBlockTypeId()).getName() + "已经存在~");
            }
        });
        TemplateGroupMap templateGroupMap = new TemplateGroupMap();
        templateGroupMap.setGroupId(groupId);
        templateGroupMap.setTemplateId(templateId);
        return this.save(templateGroupMap);
    }

    @Override
    public Boolean removeTemplateGroupMap(RemoveTemplateGroupMapReq req) {
        LambdaQueryWrapper<TemplateGroupMap> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateGroupMap::getGroupId, req.getGroupId());
        wrapper.eq(TemplateGroupMap::getTemplateId, req.getTemplateId());
        return this.remove(wrapper);
    }

    @Override
    public List<TemplateResp> findByGroupId(long groupId) {
        LambdaQueryWrapper<TemplateGroupMap> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateGroupMap::getGroupId, groupId);
        List<TemplateGroupMap> list = this.list(wrapper);
        // 通过stream流获取模板IDs
        List<Long> templateIds = list.stream().map(TemplateGroupMap::getTemplateId).toList();
        if (CollectionUtils.isEmpty(templateIds)) {
            return new ArrayList<>();
        }
        // 查询所有的模板信息
        List<Template> templates = this.templateService.listByIds(templateIds);
        List<TemplateResp> templateList = SmartPageUtil.convert(templates, TemplateResp.class);
        List<Type> typeList = this.typeService.list();
        templateList.forEach(items -> {
            for (Type type : typeList) {
                if (items.getBlockTypeId() == type.getId()) {
                    items.setBlockType(SmartPageUtil.convert(type, TypeResp.class));
                }
            }
        });
        return templateList;
    }
}